@section('css')
    {{--百度umeditorcss文件--}}
    <link rel="stylesheet" href="{{asset('admin-lte/plugins/umeditor1_2_3-utf8-php/themes/default/css/umeditor.css')}}">
    <link rel="stylesheet" href="{{asset('admin-lte/plugins/bootstrap-fileinput-4.4.8/css/fileinput.css')}}">
    {{--<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" media="all" rel="stylesheet" type="text/css"/>--}}
    <link rel="stylesheet" href="{{asset('admin-lte/plugins/iCheck/square/_all.css')}}">
    <link rel="stylesheet" href="{{asset('css/spu/property.css')}}">
    <style>
        .toplevel{
            color:#ccc;
        }
        .nextlevel{
            color: #41afff;
        }
    </style>
@stop


<div class="row">
    <div class="col-12">
        <form role="form" method="post" id="validation-form" action="{{$action=='create'?url('admin/spu/docreate'):url('admin/spu/doedit')}}">
            {{csrf_field()}}
            <div class="alert alert-danger" style="display: none">
                <h4>表单提交失败：</h4>
                <ul>
                    {{--<li><i class="glyphicon glyphicon-remove"></i>商品名称不能为空</li>--}}
                </ul>
            </div>

            <!-- Custom Tabs -->
            <div class="card">
                <div class="card-header d-flex p-0">
                    <ul class="nav nav-pills p-2">
                        <li class="nav-item"><a class="nav-link active" href="#tab_1" data-toggle="tab">基本信息</a></li>
                        <li class="nav-item"><a class="nav-link" href="#tab_2" data-toggle="tab">商品详情</a></li>
                        <li class="nav-item"><a class="nav-link" href="#tab_3" data-toggle="tab">商品图片</a></li>
                        {{--<li class="nav-item"><a class="nav-link" href="#tab_4" data-toggle="tab">商品规格</a></li>--}}
                        @if($action=='create')
                            <li class="nav-item" style ="margin-left:5em"><button class="btn btn-success">创建商品</button></li>
                        @endif
                        @if($action=='edit')
                            <li class="nav-item" style ="margin-left:5em"><button class="btn btn-success">编辑商品</button></li>
                        @endif
                    </ul>
                </div><!-- /.card-header -->
                <div class="card-body">
                    <div class="tab-content">
                        <div class="tab-pane active" id="tab_1">
                            @include('admin.spu.tabpart.general')
                        </div>
                        <!-- /.tab-pane -->
                        <div class="tab-pane" id="tab_2">
                            @include('admin.spu.tabpart.detail')
                        </div>
                        <!-- /.tab-pane -->
                        <div class="tab-pane" id="tab_3">
                            @include('admin.spu.tabpart.image')
                        </div>

                        {{--商品规格需要启用的时候开启--}}
                        {{--<div class="tab-pane" id="tab_4">--}}
                            {{--@include('admin.spu.tabpart.property')--}}
                        {{--</div>--}}
                        <!-- /.tab-pane -->
                    </div>
                    <!-- /.tab-content -->
                </div><!-- /.card-body -->
            </div>
        </form>
        <!-- ./card -->
    </div>
    <!-- /.col -->
</div>

@section('script')
    <script src="{{asset('admin-lte/plugins/iCheck/icheck.js')}}"></script>
    {{--百度umeditor插件引入--}}
    <script src="{{asset('admin-lte/plugins/umeditor1_2_3-utf8-php/umeditor.config.js')}}"></script>
    <script src="{{asset('admin-lte/plugins/umeditor1_2_3-utf8-php/umeditor.js')}}"></script>

    {{--bootstrapfile-input插件--}}
    <script src="{{asset('admin-lte/plugins/bootstrap-fileinput-4.4.8/js/plugins/sortable.js')}}" type="text/javascript"></script>
    <script src="{{asset('admin-lte/plugins/bootstrap-fileinput-4.4.8/js/fileinput.js')}}" type="text/javascript"></script>
    <script src="{{asset("admin-lte/plugins/bootstrap-fileinput-4.4.8/js/locales/zh.js")}}" type="text/javascript"></script>
    {{--主题切换--}}
    {{--<script src="../themes/explorer-fa/theme.js" type="text/javascript"></script>--}}
    <script src="{{asset("admin-lte/plugins/bootstrap-fileinput-4.4.8/themes/fa/theme.js")}}" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" type="text/javascript"></script>

    {{--jqueryVlaition插件--}}
    <script src="{{asset('admin-lte/plugins/jquery-validation/js/jquery.validate.js')}}"></script>
    <script src="{{asset('js/spu/form-validate.js')}}"></script>

    {{--layer插件--}}
    <script src="{{asset("admin-lte/plugins/layer-v3.1.1/layer.js")}}" type="text/javascript"></script>

    {{--<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" type="text/javascript"></script>--}}
    <script>
        var upload_url = '{{url('admin/spu/uploadImg')}}',
            index_url = '{{url('admin/spu/index')}}',
            delImgUrl = '{{url('admin/spu/delImg')}}',
            bsconfigUrl = '{{url('admin/spu/bsconfig')}}',
            spu_id = '{{request()->route('spu_id')}}';
            csrf = '{{csrf_token()}}';
        var controlelr = {
            bsfinput:{},//bootstrapfileinput插件堆箱
            um:{},//umeditor插件对象
            init : function(){
                this.bindEvents();
                var that = this;
                // this.renderErrorMessage('商品规格不能为空');
            },
            bindEvents:function(){
                var that = this;

                //对uneditor初始化
                this.umeditorInint();

                //bootstrapfileinput插件初始化
                this.initBootstrap();

                //jqVlidation初始化
                this.validationInit();

                //bootstrapfileinput删除图片的事件
                $('#file-fr').on('filebeforedelete',function(event, key, data){return that.onBeforeDelete(event, key, data)});
//                $('#file-fr').on('fileuploaded', function(event, data, previewId, index) {
//                    console.log(data)
//                });

                //给属性的属性值的checkbox添加change事件
                $('#dropzone').on('ifChanged',':checkbox',$.proxy(this.onchangevalcheckbox,this));

                //给商品规格的checkbox添加事件
                $('.spec-title-box').on('ifClicked',':checkbox',$.proxy(this.onchangepropcheckbox,this));

                //商品规格栏的icheck初始化
                $('input[type="checkbox"]').iCheck({checkboxClass: 'icheckbox_square-blue', radioClass: 'iradio_square-blue', cursor:true,});

                //批量按钮添加事件
                $('#sku_table')
                    .on('click','.batch-edit',$.proxy(this.onclickbatchbtn,this))
                    .on('click','.batch-close',$.proxy(this.onclickbatchinputoff,this)) //给批量设置的框添加关闭按钮事件
                    .on('click','.btn_batch_set',$.proxy(this.onclickbatchyesbtn,this))

                $('#tab_3').on('click','.btn-set-main-iamge',$.proxy(this.onclickSetMainImg,this));
            },
            initBootstrap:function(){
                this.getBsConfing();
            },
            //对uneditor初始化
            umeditorInint:function(){
                this.um =   UM.getEditor('container', {
                });
                // var html = um.getContent();
                // var txt = um.um.getContentTxt();
                //um.setContent('要设置的编辑器内容.')
            },

            //对bootstrapfileinput的js初始化
            bootstrapFileInputInit:function(bsconfig){
                var options = $.extend({
                    theme: "fa",
                    language: 'zh',
                    required:true,
                    uploadUrl: upload_url,//异步上传的地址
                    showUpload:false,//底部的上传按钮显示
                    overwriteInitial:false, //是否覆盖预览图片 默认为true 这里设置为false
                    showRemove:false,
                    autoReplace:false,
                    showClose:false,
                    maxFileSize:'1090',//上传文件的最大大小
                    deleteUrl:delImgUrl,//删除文件的url

                    uploadExtraData:{
                        _token : csrf
                    },//上传的额外上传项
                    //预览图片的显示
//                    initialPreview: [
//                        "<img src='/images/desert.jpg' class='file-preview-image' alt='Desert' title='Desert'>",
//                        "<img src='/images/jellyfish.jpg' class='file-preview-image' alt='Jelly Fish' title='Jelly Fish'>",
//                    ],
//                    initialPreviewConfig: [
//                        {
//                            caption: 'desert.jpg',
////                            width: '120px',
//                            url: '/localhost/avatar/delete',//删除链接
//                            key: 100,
//                            extra: {id: 100}
//                        },
//                        {
//                            caption: 'jellyfish.jpg',
////                            width: '120px',
//                            url: '/localhost/avatar/delete',//删除链接
//                            key: 101,
//                            frameClass: 'my-custom-frame-css',
//                            frameAttr: {
//                                style: 'height:80px',
//                                title: 'My Custom Title',
//                            },
//                            extra: function() {
//                                //删除时要额外传递给后台的内容
//                                return {id: $("#id").val()};
//                            },
//                        }
//                    ],
                    //以下两个选项需要一起配置，配置自定义的按钮显示形式
                    layoutTemplates:{
                        actions: '<div class="file-actions">\n' +
                        '    <div class="file-footer-buttons">\n' +
                        '        {upload} {download} {delete} {zoom} {other} {default}<span class="bs-hidden-input">{hidden_input}</span>' +
                        '    </div>\n' +
                        '    {drag}\n' +
                        '    <div class="clearfix"></div>\n' +
                        '</div>',
                    },
                    previewThumbTags : {
                        '{default}': '',
                        '{hidden_input}': '',
                    },
//                    initialPreviewThumbTags:[
//                        {
//                         '{default}': '<span class="btn btn-default btn-sm btn-set-main-iamge">设为主图</span>',
//                         '{hidden_input}':'<input type="hidden" value="0" name="Image[default][]">'+
//                         '<input type="hidden" value="0" name="Image[key][]">'+
//                         '<input type="hidden" value="url" name="Image[url][]">',
//                        },
//                        {'{default}': '<span class="btn btn-success btn-sm bs-main">主图</span>','{hidden_input}':''},
//                    ],
                    maxFileCount:6,//最多10张图片
                    showCancel:false,//在ajax上传时候才会显示
                    allowedFileExtensions: ['jpg', 'png', 'gif','bmp','jpeg'],
                    //配置图片预览上面的各个按钮的显示情况 包括配置在previe上的图片
                    fileActionSettings:{
//                        showUpload:false,
//                        showRemove:false,
                    },
                },bsconfig);
                this.bsfinput = $('#file-fr').fileinput(options);
            },

            //图片删除之前的事件(主要用于提示)
            onBeforeDelete:function(event, key, data){
                return new Promise(function(resolve, reject) {
                    layer.confirm('确定要删除该图片吗?',function(){
                        resolve();
                        layer.msg('删除成功');
                    })
                });

            },
            //点击批量设置的按钮的事件
            onclickbatchbtn:function(e){
                $target = $(e.target);
                $('.batch-input').hide();
                $target.closest('.batch').find('.batch-input').show();
            },

            //给批量设置的框添加关闭按钮事件
            onclickbatchinputoff:function(e){
                var $target = $(e.target);
                $target.closest('.batch-input').hide();
            },

            //批量设置确认事件
            onclickbatchyesbtn:function(e){
                var $target = $(e.target),
                    tdIndex = $target.closest('th').index() ,
                    input_val = $target.prev().val();

                $.each($('#sku_table tbody tr'),function(k,v){
                    $(v).find('td').eq(tdIndex).find(':text').val(input_val);
                })

                $target.closest('.batch-input').hide();
            },

            //切换属性值的checkbox
            onchangevalcheckbox:function(e){
                var _this = this,
                    $target = $(e.target);

                //这边icheck点击的时候 会去渲染dom，导致获取按钮状态会延迟
                var index = layer.load(0, {
                    shade: [0.5,'#fff'] //0.1透明度的白色背景
                });
                setTimeout(function(){
                    layer.close(index);
                    _this.regenerate_sku_data();
                    _this.render_sku_table();
                },500)

            },

            onchangepropcheckbox:function(e){
                //这边icheck点击的时候 会去渲染dom，导致获取按钮状态会延迟
                var index = layer.load(0, {
                    shade: [0.5,'#fff'] //0.1透明度的白色背景
                });
                var $target = $(e.target),
                    _this   = this,
                    checkboxIndex = $('.spec-values-item').index($target.closest('.spec-values-item'));
                setTimeout(function(){
                    layer.close(index);
                    ischecked = $target.prop('checked');
                    if(ischecked){
                        //选中属性后将相应的属性值的列表显示，并清空属性列表的父级元素 span的class清空
                        $('.goods-spec-item').eq(checkboxIndex).show();
                    }else{
                        //失去选中属性后，将相应的属性值的列表隐藏，并清空属性列表的父级元素 span的class清空
                        $('.goods-spec-item').eq(checkboxIndex).hide().find('.spec-values input').iCheck('uncheck');
                        // $('input').iCheck('uncheck');
                        //重新渲染 sku-table
                        _this.render_sku_table();
                    }
                },500)

            },

            //点击设置主图的事件函数
            onclickSetMainImg:function(e){
                var $btn = $(e.target),
                    $input_div = $btn.next();
                //将主图的样式和隐藏域修改
                $('#tab_3').find('.bs-main')
                    .removeClass('btn-success bs-main').addClass('btn-default btn-set-main-iamge').html('设为主图')
                    .next().find('input[name="Image[default][]"]').val(0);

                //将当前的input的默认图片的隐藏域设置为1，
                $input_div.find('input[name="Image[default][]"]').val('1')
                    .end().prev().removeClass('btn-default btn-set-main-iamge').addClass('btn-success bs-main').html('主图');

            },
            //根据
            //计算笛卡尔乘积
            CartesianZ:function(data){
                // 参数形如 data = [
                //     [
                //         {spec_id :103,spec_name: '颜色',spec_value:'红色',spec_value_id:1},
                //         {spec_id :103,spec_name: '颜色',spec_value:'蓝色',spec_value_id:2},
                //     ],
                //     [
                //         {spec_id :102,spec_name: '逼格',spec_value:'高',spec_value_id:1},
                //         {spec_id :102,spec_name: '逼格',spec_value:'低',spec_value_id:2},
                //     ],
                // ];
                var Cartesian = function(a,b){
                    var data = [];
                    for(var i = 0 ; i < a.length; i++){
                        for(var j = 0 ; j < b.length ; j++){
                            data.push(array(a[i],b[j]));
                        }
                    }
                    return data;
                };

                var array = function(a,b){
                    var ret=[];
                    if(!(a instanceof Array)){
                        ret=Array.call(null,a);
                    }
                    else{
                        ret=Array.apply(null,a);
                    }

                    ret.push(b);
                    return ret;
                };

                var len = data.length;

                if(len == 0){
                    return [];
                }else if(len == 1){
                    var tmp = [];
                    $.each(data[0],function(k,v){
                        tmp.push([v]);
                    });
                    return tmp;
                }else{
                    var ret=data[0];
                    for(var i=1;i<len;i++){
                        ret=Cartesian(ret,data[i]);
                    }
                    return ret;
                }
            },

            //渲染sku-table的函数
            render_sku_table:function() {
                var data = this.CartesianZ(this.regenerate_sku_data()); //重新用笛卡尔乘积生成的data数组
                var thead_th_val_html = '';
                var tbody_tr_val_html = '';
                var val_td_html = '';
                var html = '';

//                console.log(data);
                if (data.length > 0) {
                    //隐藏提示框
                    $('#sku_table_warning').hide();

                    //渲染table中的头部
                    $.each(data[0],function(k,v){
                        thead_th_val_html += '<th class="spec-th th_spec_id_'+v.props_id+'">'+v.props_name+'</th>\n';
                    });

                    //渲染table中的body部分
                    $.each(data,function(k,v){
                        val_td_html = '';

                        //遍历第二层
                        $.each(v,function(kk,vv){
                            val_td_html += '<td class="spec-vname-td">\n' +
                                '              <span class="spec-vname-label spec-vname-label-'+vv.props_value_id+'" data-attr-id="'+vv.props_id+'">'+vv.props_value_name+'</span>\n' +
                                '              <input type="hidden" name="specs['+k+']['+vv.props_id+'][attr_id]" value="'+vv.props_id+'">\n' +
                                '              <input type="hidden" name="specs['+k+']['+vv.props_id+'][disabled]" value="false">\n' +
                                '              <input type="hidden" name="specs['+k+']['+vv.props_id+'][attr_vid]" value="'+vv.props_value_id+'" class="spec-vid-text-1073" data-attr-id="'+vv.props_id+'">\n' +
                                '              <input type="hidden" name="specs['+k+']['+vv.props_id+'][attr_vname]" value="'+vv.props_value_name+'" class="spec-vname-text-1073" data-attr-id="'+vv.props_id+'">\n' +
                                '              <input type="hidden" name="specs['+k+']['+vv.props_id+'][attr_desc]" value="" class="spec-desc-text-1073" data-attr-id="'+vv.props_id+'">\n' +
                                '        </td>';
//                            console.log(vv);

                        });

                        tbody_tr_val_html += '<tr>\n' +
                            '                        <td class="sku-td-index text-c">'+(parseInt(k)+1)+'<!--<a class="del-btn sku-item-handle" data-sku-enable="false" data-sku-index="1" title="点击禁用此规格">×</a>!--></td>\n'    +
                            val_td_html+
                            '\n' +
                            '                        <td class="sku-market-price-td ">\n' +
                            '                            <input type="text" name="sku['+k+'][price]" value="" class="form-control w60 sku-field sku-market-price" data-rule-min="0.01" data-msg-min="市场价必须是大于0的数字" data-msg-required="价格不能为空"  data-rule-required="true">\n' +
                            '                        </td>\n' +
                            '                        <td class="sku-goods-price-td ">\n' +
                            '                            <input  type="text" name="sku['+k+'][discount_money]" value="" class="form-control w60 sku-field sku-goods-price" data-rule-required="false" data-msg-required="折扣价不能为空" data-rule-min="0" data-msg-min="折扣价必须是大于等于0的数字" data-msg-decimal="折扣价必须是一个数字">\n' +
                            '                        </td>\n' +
                            '                        <td>\n' +
                            '                            <input required type="text" name="sku['+k+'][store]" value="" class="form-control small sku-field sku-goods-number" data-msg-required="库存不能为空" data-rule-min="0" data-msg-min="库存必须大于等于0">\n' +
                            '                        </td>\n' +
                            '                        <td>\n' +
                            '                            <input required type="text" name="sku['+k+'][bn]" value="" class="form-control small sku-field sku-goods-number" data-rule-required="true" data-msg-required="货号不能为空">\n' +
                            '                        </td>\n' +
                            '                   </tr>';

                    });

                    //开始渲染table表格
                    html = '              <thead>\n' +
                        '                    <tr>\n' +
                        '                        <th class="sku-th-index">序号</th>\n' +
                        thead_th_val_html+
                        '                        <th class="sku-market-price-td ">\n' +
                        '                            <span class="text-danger ng-binding">*</span>\n' +
                        '                            价格\n' +
                        '                            <div class="batch">\n' +
                        '                                <a href="javascript:void(0);" class="batch-edit" title="批量设置">\n' +
                        '                                    <i class="fa fa-edit"></i>\n' +
                        '                                </a>\n' +
                        '                                <div class="batch-input" style="display: none;">\n' +
                        '                                    <h6>批量设置价格：</h6>\n' +
                        '                                    <a href="javascript:void(0);" class="batch-close">X</a>\n' +
                        '                                    <input type="text" class="form-control text small pull-none valid" value="" aria-invalid="false">\n' +
                        '                                    <input type="button" class="btn btn-primary btn-sm pull-none m-l-5 btn_batch_set" data-field="market_price" value="设置">\n' +
                        '                                    <span class="arrow"></span>\n' +
                        '                                </div>\n' +
                        '                            </div>\n' +
                        '                        </th>\n' +
                        '                        <th class="sku-goods-price-td ">\n' +
                        '                            <span class="text-danger ng-binding">*</span>\n' +
                        '                            折扣价\n' +
                        '                            <div class="batch">\n' +
                        '                                <a href="javascript:void(0);" class="batch-edit" title="批量设置">\n' +
                        '                                    <i class="fa fa-edit"></i>\n' +
                        '                                </a>\n' +
                        '                                <div class="batch-input" style="display: none;">\n' +
                        '                                    <h6>批量设置折扣价：</h6>\n' +
                        '                                    <a href="javascript:void(0);" class="batch-close">X</a>\n' +
                        '                                    <input class="form-control text small pull-none valid" type="text" value="" aria-invalid="false">\n' +
                        '                                    <input type="button" class="btn btn-primary btn-sm pull-none m-l-5 btn_batch_set" data-field="goods_price" value="设置">\n' +
                        '                                    <span class="arrow"></span>\n' +
                        '                                </div>\n' +
                        '                            </div>\n' +
                        '                        </th>\n' +
                        '                        <th>\n' +
                        '                            <span class="text-danger ng-binding">*</span>\n' +
                        '                            库存\n' +
                        '                            <div class="batch">\n' +
                        '                                <a href="javascript:void(0);" class="batch-edit" title="批量设置">\n' +
                        '                                    <i class="fa fa-edit"></i>\n' +
                        '                                </a>\n' +
                        '                                <div class="batch-input" style="display: none;">\n' +
                        '                                    <h6>批量设置库存：</h6>\n' +
                        '                                    <a href="javascript:void(0);" class="batch-close">X</a>\n' +
                        '                                    <input class="form-control text small pull-none" type="text" value="">\n' +
                        '                                    <input type="button" class="btn btn-primary btn-sm pull-none m-l-5 btn_batch_set" data-field="goods_number" value="设置">\n' +
                        '                                    <span class="arrow"></span>\n' +
                        '                                </div>\n' +
                        '                            </div>\n' +
                        '                        </th>\n' +
                        '                        <th>\n' +
                        '                            <span class="text-danger ng-binding">*</span>\n' +
                        '                            商品货号\n' +
                        '                            <div class="batch">\n' +
                        '                                <a href="javascript:void(0);" class="batch-edit" title="批量设置">\n' +
                        '                                    <i class="fa fa-edit"></i>\n' +
                        '                                </a>\n' +
                        '                                <div class="batch-input" style="display: none;">\n' +
                        '                                    <h6>批量设置货号：</h6>\n' +
                        '                                    <a href="javascript:void(0);" class="batch-close">X</a>\n' +
                        '                                    <input class="form-control text small pull-none" type="text" value="">\n' +
                        '                                    <input type="button" class="btn btn-primary btn-sm pull-none m-l-5 btn_batch_set" data-field="goods_number" value="设置">\n' +
                        '                                    <span class="arrow"></span>\n' +
                        '                                </div>\n' +
                        '                            </div>\n' +
                        '                        </th>\n' +
                        '                    </tr>\n' +
                        '                </thead>\n' +
                        '                <tbody>\n' +
                        tbody_tr_val_html+
                        '</tbody>';
                    $('#sku_table').html(html);
                    return true;
                }
                $('#sku_table_warning').show();
                $('#sku_table').html(html);
                return false;
            },

            //重新组成 sku data的信息
            regenerate_sku_data : function(){
                var display,
                    $val_input,
                    data = [];

                //遍历属性
                $.each($('.goods-spec-item'),function(k,v){
                    display = $(v).css('display');
                    if(display === 'block'){
                        //遍历下面的属性值
                        var pro_data = [];
                        $.each($(v).find('.spec-values label'),function(kk,vv){
                            $val_input = $(vv).find('.checked input');
                            if($val_input.length > 0){
                                pro_data.push({
                                    props_id        : $val_input.data('attr-id'),
                                    props_name      : $val_input.data('attr-name'),
                                    props_value_id  : $val_input.data('vid'),
                                    props_value_name: $val_input.data('vname'),
                                });
                            }

                        });
                        if(pro_data.length>0){data.push(pro_data)}
                    }
                });
                console.log('点击属性值生成的新数据是');
                console.log(data);
                return data;
            },

            //获取bootstrapfileinput初始化图片配置列表
            getBsConfing:function(){
                var that = this;
                $.get(bsconfigUrl+'/'+spu_id,{},function(data){
                    that.bootstrapFileInputInit(data);
                })
            },
            /**
             * 显示错误的公共方法
             */
            renderErrorMessage:function(error,attribute)
            {
                var errorsArr = [],
                    html = '';
                var errorLi = $('.alert.alert-danger ul').find('#'+attribute);

                if(error){
                    $('.alert.alert-danger').show();
                    html =  '<li id="'+attribute+'"><i class="glyphicon glyphicon-remove"></i>'+error+'</li>';


                    if(errorLi.length>0){
                        return ;
                    }else{
                        $('.alert.alert-danger ul').append(html);
                    }
                }else{
                    errorLi.remove();
                    if($('.alert.alert-danger li').length == 0){
                        $('.alert.alert-danger').hide();
                    }
                }
            },

            //验证商品图片是否已经上传
            validateUploadImg:function(){
                var $preiveContainer = $('#tab_3 .file-preview-thumbnails .file-preview-frame');
                var flag = true;
                if($preiveContainer.length>0){
                    $.each($preiveContainer,function(k,v){
                        console.log(!$(v).find('.bs-hidden-input').html());
                        if(!$(v).find('.bs-hidden-input').html()){
                            flag = false;
                            return ;
                        }
                    })
                    return flag;
                }

                return false;
            },


            //jqvalidation验证字段有效性
            validationInit:function(){
                var form1 = $('#validation-form');
                var that = this;
                if ($.validator) {
                    $.validator.prototype.elements = function () {
                        var validator = this,
                            rulesCache = {};

                        return $(validator.currentForm)
                            .find("input, select, textarea")
                            .not(":submit, :reset, :image, [disabled]")
                            .not(this.settings.ignore)
                            .filter(function () {
                                if (!this.name && validator.settings.debug && window.console) {
                                    console.error("%o has no name assigned", this);
                                }
                                //注释这行代码
                                // select only the first element for each name, and only those with rules specified
                                if(!validator.objectLength($(this).rules())){
                                    return false;
                                }
                                //if ( this.name in rulesCache || !validator.objectLength($(this).rules()) ) {
                                //    return false;
                                //}
                                rulesCache[this.name] = true;
                                return true;
                            });
                    }
                }

                form1.validate({
                    debug:true,
                    focusInvalid: false, // do not focus the last invalid input
                    ignore: ".edui-container input,.file-caption-name,.btn_batch_set,.pull-none,:checkbox",  // validate all fields including form hidden input
                    messages: {
                        'Goods[name]':{'required':'商品名称不能为空'},
                        'Goods[bn]':{'required':'商品编号不能为空'},
                        'Goods[cat_id]':{'required':'商品分类不能为空'},
                        'Goods[sort]':{'required':'商品排序不能为空','number':'商品排序必须为数字'},
                        'Goods[price]':{'required':'商品价格不能为空',number:'商品价格必须是数字'},
                        'Goods[discount_price]':{'required':'折扣价不能为空',number:'折扣价必须是数字'},
                        'Goods[stock]':{'required':'库存不能为空',number:'库存必须是数字'},
                    },
                    rules: {
                        'Goods[name]':{'required':true},
                        'Goods[bn]':{'required':true},
                        'Goods[cat_id]':{'required':true},
                        'Goods[sort]':{'required':true,number:true},
                        'Goods[price]':{'required':true,number:true},
                        'Goods[discount_price]':{'required':true,number:true},
                        'Goods[stock]':{'required':true,number:true},
                    },

                    invalidHandler: function (event, validator) { //display error alert on form submit
                        // console.log(validator);
                        //验证商品图片是否已经上传
                        if(!that.validateUploadImg()){
                            that.renderErrorMessage('商品图片没有上传！','uploadImgError');
                        }else{
                            that.renderErrorMessage(null,'uploadImgError');
                        }
                    },

                    //当某个字段验证成功之后的回调事件
                    success: function (label) {
                        label.parent().remove();

                        if($('.alert.alert-danger li').length == 0){
                            $('.alert.alert-danger').hide();
                        }

                    },

                    //自定义错误显示逻辑
                    showErrors:function(errorMap,errorList,validator){
                        var i, elements, error;
                        for ( i = 0; i < errorList.length; i++ ) {
                            error = errorList[ i ];
                            if($(error.element).parent().is('td')){
                                //则是商品规格的验证
                                var trindex = $(error.element).closest('tr').index()+1;
                                error.message = '商品规格-序号'+trindex+'&nbsp;详情：'+error.message;
                            }
                            validator.showLabel( error.element, error.message );
                        }
                        if ( errorList.length ) {
                            validator.toShow = validator.toShow.add( validator.containers );
                        }
                        if ( validator.settings.success ) {
                            for ( i = 0; validator.successList[ i ]; i++ ) {
                                validator.showLabel( validator.successList[ i ] );
                            }
                        }
                        validator.toHide = validator.toHide.not( validator.toShow );
                        validator.hideErrors();
                        validator.addWrapper( validator.toShow ).show();
                    },

                    //指定每个错误错误存放的位置
                    errorPlacement:function(error,element) {
                        $('.alert.alert-danger').show();
                        var errorLi = error.wrap('<li></li>').parent();
                        $('.alert.alert-danger ul').append(errorLi);
                    },
                    submitHandler: function(form){
                        //验证商品图片是否已经上传
                        if(!that.validateUploadImg()){
                            that.renderErrorMessage('商品图片没有上传！','uploadImgError');
                            return false;
                        }else{
                            that.renderErrorMessage(null,'uploadImgError');
                        }

                        var index = layer.load(0, {
                            shade: [0.5,'#fff'] //0.1透明度的白色背景
                        });
                         <!--$('#validation-form').attr('action','{{url('admin/spu/doedit')}}').get(0).submit();-->

                        $.ajax({
                            type:"POST",
                            url : $('#validation-form').attr('action'),
                            data : $('#validation-form input,#validation-form textarea,#validation-form select').not('.kv-zoom-cache input').serialize()+'&_token='+csrf,
                            success:function(data){
                              layer.close(index);
                              layer.alert(data.msg);
                              if(data.ret == 200){
                                  setTimeout(function(){
                                      location.href = index_url;
                                  },1500)
                              }
                            },

                        })
                    }
                });
            }

        };
        $(function(){
            controlelr.init();
        });
    </script>
@stop